<template>
	<div style="height:calc(100vh - 94px);background-color:#FFFFFF;overflow-y:auto;">
		<pheader style="border-bottom: 1px solid #dcdae2; ">
			<div  slot="left">网路策略配置</div>
			<div style="float:right;position: relative;font-weight: normal;" slot="right">
				<Row>
					<Col span="4">
						<Button type="primary" size="small" @click="add()" v-if="this.$hasPerm('netAddue')">新增</Button>
					</Col>
					<Col span="20" style="padding-left:12px">
						<Input v-model="search_param" search placeholder="请输入模板名称" style="width: auto;" @on-search="changePage($event,0)" />
					</Col>
				</Row>
				
			</div>
		</pheader>
		
		<template style="padding: 8px 8px 0px 8px;">
			<div style="width: 100%;background-color: white;height: calc(100vh - 152px);overflow-y: auto;padding:10px;">

				<Table border stripe :columns="severColumns" :data="startegies">
					<template  slot-scope="{ row, index }" slot="direction" >
						<span >{{row.oriPool + '（到）'+ row.tarPool}}</span>
					</template>
				</Table>

				<div style="margin: 10px;overflow: hidden">
					<div style="float: right;">
						<Page :current="page" :total="total_num" show-total show-elevator show-sizer @on-change="changePage"
						 @on-page-size-change="changePageSize"></Page>
					</div>
				</div>


				<div v-if="add_startegies.show">
					<Modal @on-ok="add_startegies_ok()" @on-cancel="cancel('add_startegies')" v-model="add_startegies.show" :loading="loading" :title="!add_startegies.isupdate?'新增模板':'编辑模板'"
					 width="80%">
						<Form ref="add_startegies" :model="add_startegies" :rules="ruleInline" label-position="left" :label-width="120">
							<Row>
								<Col span="8">
								<FormItem label="模板名称:" prop="title">
									<Input v-model="add_startegies.title"/>
								</FormItem>
								</Col>
							</Row>
							<Row>
								<Col span="8">
								<FormItem label="源资源池:" prop="oriPool">
									<Select v-model="add_startegies.oriPool" :transfer='true' style="z-index:999">
										<Option value="哈尔滨资源池">哈尔滨资源池</Option>
										<Option value="呼和浩特资源池">呼和浩特资源池</Option>
										<Option value="业支非池化">业支非池化</Option>
										<Option value="信息港资源池">信息港资源池</Option>
										<Option value="省公司">省公司</Option>
										<Option value="专业公司">专业公司</Option>
										<Option value="其他">其他</Option>
									</Select>
								</FormItem>
								</Col>
								<Col span="8" class="col_left">
								<FormItem label="目的资源池:" prop="tarPool">
									<Select v-model="add_startegies.tarPool" :transfer='true' style="z-index:999">
										<Option value="哈尔滨资源池">哈尔滨资源池</Option>
										<Option value="呼和浩特资源池">呼和浩特资源池</Option>
										<Option value="业支非池化">业支非池化</Option>
										<Option value="信息港资源池">信息港资源池</Option>
										<Option value="省公司">省公司</Option>
										<Option value="专业公司">专业公司</Option>
										<Option value="其他">其他</Option>
									</Select>
								</FormItem>
								</Col>
							</Row>
							<Row>
								<Col span="8">
								<FormItem label="策略类型:" prop="netType">
									<Select v-model="add_startegies.netType" :transfer='true' style="z-index:999">
										<Option value="公网">公网</Option>
										<Option value="承载网">承载网</Option>
										<Option value="内网">内网</Option>
										<Option value="专线">专线</Option>
										<Option value="CMNetDCI_vpn">CMNetDCI_vpn</Option>
									</Select>
								</FormItem>
								</Col>
							</Row>
							<Row>
								<Col span="8">
								<FormItem label="源接入系统:" prop="oriSys">
									<Select v-model="add_startegies.oriSys" :transfer='true' filterable>
										<Option v-for="(item,index) in allSysList" :value="item.sysName" :key="index">{{item.sysName}}</Option>
										<Option value="外部系统">外部系统</Option>
									</Select>
								</FormItem>
								</Col>
								<Col span="8" class="col_left">
									<FormItem label="目的接入系统:" prop="tarSys">
										<Select v-model="add_startegies.tarSys" :transfer='true' filterable>
											<Option v-for="(item,index) in allSysList" :value="item.sysName" :key="index">{{item.sysName}}</Option>
											<Option value="外部系统">外部系统</Option>
										</Select>
									</FormItem>
								</Col>
							</Row>

                <Button size="small" class="data_button" @click="addNetworkInfoList">新增策略</button>
                <Row style="padding-top: 10px;overflow-x:auto" id="startegies">
                    <Table  size="small"  :columns="severColumns2" :data="add_startegies.startegies" border>
                        <template slot-scope="{ row, index }" slot="index" >
                            <p>{{index+1}}</p>
                        </template>
                        <template slot-scope="{ row, index }" slot="direction" >
							<Input type="textarea" :autosize="{minRows: 1,maxRows: 10}" v-model="add_startegies.startegies[index].direction" />
                            <!-- <Input type="textarea" :autosize="{minRows: 1,maxRows: 10}" v-model="add_startegies.startegies[index].oriPool" />
                            {{'(到)'}}
                            <Input type="textarea" :autosize="{minRows: 1,maxRows: 10}" v-model="add_startegies.startegies[index].tarPool" /> -->
                        </template>
                        <template slot-scope="{ row, index }" slot="oriAddr" >
                            <Input type="textarea" :autosize="{minRows: 1,maxRows: 999}" v-model="add_startegies.startegies[index].oriAddr" /> 
							<!-- <textarea style="width:100%" v-model="add_startegies.startegies[index].oriAddr" /> -->
                        </template>
                        <template slot-scope="{ row, index }" slot="oriMapAddr" >
                            <Input type="textarea" :autosize="{minRows: 1,maxRows: 999}" v-model="add_startegies.startegies[index].oriMapAddr" />
                        </template>
                        <template slot-scope="{ row, index }" slot="oriPortFrom" >
                            <!-- <Input v-model="add_startegies.startegies[index].oriPortFrom" /> -->
							<Select v-model="add_startegies.startegies[index].oriPortFrom" :transfer='true' filterable>
								<Option value="不限">不限</Option>
								<Option value="1：65535">1：65535</Option>
							</Select>
                        </template>
                        <!-- <template slot-scope="{ row, index }" slot="oriPortTo" >
                            <Input v-model="add_startegies.startegies[index].oriPortTo" />
                        </template> -->
                        <template slot-scope="{ row, index }" slot="targetAddr" >
                            <Input  type="textarea" :autosize="{minRows: 1,maxRows: 999}" v-model="add_startegies.startegies[index].targetAddr" />
                        </template>
                        <template slot-scope="{ row, index }" slot="targetMapAddr" >
                            <Input type="textarea" :autosize="{minRows: 1,maxRows: 999}" v-model="add_startegies.startegies[index].targetMapAddr" />
                        </template>
                        <template slot-scope="{ row, index }" slot="targetPortfrom" >
                            <Input v-model="add_startegies.startegies[index].targetPortfrom" />
                        </template>
                        <!-- <template slot-scope="{ row, index }" slot="targetPortTo" >
                            <Input v-model="add_startegies.startegies[index].targetPortTo " />
                        </template> -->
                        <template slot-scope="{ row, index }" slot="tcpProtocol" >
                            <!-- <Input v-model="add_startegies.startegies[index].tcpProtocol" /> -->
							<Select v-model="add_startegies.startegies[index].tcpProtocol" :transfer='true' filterable>
								<Option value="TCP">TCP</Option>
								<Option value="UDP">UDP</Option>
							</Select>
                        </template>
                        <!-- <template slot-scope="{ row, index }" slot="udpProtocol" >
                            <Input v-model="add_startegies.startegies[index].udpProtocol" />
                        </template> -->
                        <template slot-scope="{ row, index }" slot="appProtocol" >
                            <Input v-model="add_startegies.startegies[index].appProtocol" />
                        </template>
                        <template slot-scope="{ row, index }" slot="purpose" >
                            <Input type="textarea" :autosize="{minRows: 1,maxRows: 10}" v-model="add_startegies.startegies[index].purpose" />
                        </template>
                        <template slot-scope="{ row, index }" slot="action" >
                            <!-- <Button type="primary" size="small" @click="deleteList(row,index)" :disabled="ifedit || networkInfo.startegies.length == 1">删除</Button> -->
                            <Button type="primary" size="small" @click="deleteList(row,index)" >删除</Button>
                        </template>
                    </Table>
                </Row>


						</Form>
					</Modal>
				</div>

			</div>
		</template>
	</div>
</template>

<script>
	import expandRow from '../comp_user/user_expand'
	import usermain from "../comp_user/user_main"
	import mpage from "../comp_chatter/mpage"
	import pheader from "../comp_chatter/pheader"
	import mheader from "../comp_chatter/mheader"
	import mcontainer from "../comp_chatter/mcontainer"
	import Axios from 'axios'
	import ajax from "../ajax_util"
	import md5 from 'js-md5'
	import inputSearch from '../base/input_search'

	export default {
		components: {
			expandRow,
			usermain,
			mpage,
			mheader,
			mcontainer,
			pheader,
			inputSearch
		},
		data() {
            
			return {
				severColumns2:[
                    //  {
                    //     title: "序号",
                    //     align: "center",
                    //     width: 60,
                    //     slot: "index",
                    //     fixed: 'left'
                    // },
                    {
                        title: "访问方向 (*必填)",
                        align: "center",
                        width: 200,
                        key: "direction",
                        slot: "direction",
                        // fixed: 'left'
                    },
                    {
                        title: "源地址 (*必填)",
                        align: "center",
                        width: 240,
                        key: "oriAddr",
                        slot: "oriAddr"
                    },
                    {
                        title: "源地址对应的映射IP (选填)",
                        align: "center",
                        width: 240,
                        key: "oriMapAddr",
                        slot: "oriMapAddr"
                    },
                    {
                        title: "源端口",
                        align: "center",
						width: 120,
                        key: "oriPortFrom",
                        slot: "oriPortFrom",
                        // children: [
                        //     {
                        //         title: '从',
                        //         align: 'center',
                        //         width: 110,
                        //         key: "oriPortFrom",
                        //         slot: "oriPortFrom"
                        //     },
                        //     {
                        //         title: '到',
                        //         align: 'center',
                        //         width: 110,
                        //         key: "oriPortTo",
                        //         slot: "oriPortTo"
                        //     },
                        // ]
                    },
                    {
                        title: "目的地址 (*必填)",
                        align: "center",
                        width: 240,
                        key: "targetAddr",
                        slot: "targetAddr"
                    },
                    {
                        title: "目的地址对应的映射IP (选填)",
                        align: "center",
                        width: 240,
                        key: "targetMapAddr",
                        slot: "targetMapAddr"
                    },
                    {
                        title: "目的端口 (*必填)",
                        align: "center",
						width: 130,
                        key: "targetPortfrom",
                        slot: "targetPortfrom",
                        // children: [
                        //     {
                        //         title: '从',
                        //         align: 'center',
                        //         width: 130,
                        //         key: "targetPortfrom",
                        //         slot: "targetPortfrom"
                        //     },
                        //     {
                        //         title: '到',
                        //         align: 'center',
                        //         width: 130,
                        //         key: "targetPortTo",
                        //         slot: "targetPortTo"
                        //     },
                        // ]
                    },
                    {
                        title: "传输协议 (*必填)",
                        align: "center",
						width: 130,
						key: "tcpProtocol",
						slot: "tcpProtocol",
                        // children: [
                        //     {
                        //         title: "TCP",
                        //         align: "center",
                        //         width: 100,
                        //         key: "tcpProtocol",
                        //         slot: "tcpProtocol"
                        //     },
                        //     {
                        //         title: 'UDP',
                        //         align: 'center',
                        //         width: 100,
                        //         key: "udpProtocol",
                        //         slot: "udpProtocol"
                        //     },
                        // ]
                    },

                    {
                        title: "应用层协议 (选填)",
                        align: "center",
                        width: 130,
                        key: "appProtocol",
                        slot: "appProtocol"
                    },
                    {
                        title: "策略用途 (*必填)",
                        align: "center",
                        width: 200,
                        key: "purpose",
                        slot: "purpose"
                    },
                    {
                        title: "操作",
                        align: "center",
                        width: 80,
                        slot: "action",
                        // fixed: 'right',
                    }

                ],
				allSysList:[],
                startegies:[],
				ruleInline: {
					title: [{
						required: true,
						message: '请输入模板名称.',
						trigger: 'blur'
					}],
				},
				strategyyUrl: this.CONFIG.progress_url + "/net-strategy",

				add_startegies:{
					id: "",
					title:'',
					show: false,
					isupdate: false,
					title:"",
					netType:"",
					// oriPool:"",
					// tarPool:'',
					oriSys:"",
					tarSys:"",
					startegies:[],
				},
				editIndex: "", //编辑的信息下标

				countSys: [],
				total_num: 0,

				loading: true,
				data: [],

				page: 1,
				pageSize: 10,
				search_param: '',
				url_id: '0',

				httpHeader: {
					Authorization: this.$store.state.token
				},

			}
		},
		computed: {
            severColumns(){
                let severColumns = []
                severColumns.push({
                    title: '序号',
					type: 'index',
					width: 60,
					align: 'center',
                    fixed: 'left',
					render: (h, params) => {
						return h('span', params.index + (this.page - 1) * this.pageSize + 1);
					}
                });
				severColumns.push({
                    title: "模板名称",
                    align: "center",
                    width: 200,
                    key: "title",
                });
                severColumns.push({
                    title: "访问方向 (*必填)",
                    align: "center",
                    minWidth: 300,
                    key: "direction",
                    slot: "direction",
                });
				severColumns.push({
                    title: "源接入系统",
                    align: "center",
                    width: 200,
                    key: "oriSys",
                });
				severColumns.push({
                    title: "目的接入系统",
                    align: "center",
                    width: 200,
                    key: "tarSys",
                });

                if (this.$hasPerm('netEdit') || this.$hasPerm('netMove')) {
					severColumns.push({
						title: '操作',
						key: 'action',
						width: 160,
						align: 'center',
                        fixed: 'right',
						render: (h, params) => {
							let button = [];
							if (this.$hasPerm('netEdit')) {
								button.push(
									h('Button', {
										props: {
											type: 'primary',
											size: 'small'
										},
										style: {
											marginRight: '5px'
										},
										on: {
											click: () => {
												this.edit(params)
											}
										}
									}, '编辑')
								);
							}
							if (this.$hasPerm('netMove')) {
								button.push(
									h('Button', {
										props: {
											type: 'error',
											size: 'small'
										},
										on: {
											click: () => {
												this.delete(params.row.id)
											}
										}
									}, '删除')
								);
							}
							return h('div', button);
						}
					});
				}
                return severColumns;
            },

		},
		mounted() {
			this.get_all_strategy();
			this.getAllSys();
		},
		methods: {
			isValidIP(ip) {
                var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
                return reg.test(ip);
            },
			splitIP(data){
				var result = []
				var split_1 = data.split('\n')
				split_1.forEach(item=>{
					result.push.apply(result,item.split('-'))
				})
				return result
			},
			checkIP(list){
				var result = true
				list.forEach(item=>{
					if (!this.isValidIP(item)) {
						result = false
					}
				})
				return result
			},
			handleCreateOriSys(val){
				this.add_startegies.oriSys = val;
			},
			handleCreateTarSys(val){
				this.add_startegies.tarSys = val;
			},
			addNetworkInfoList(){
                console.log('this.networkInfo',this.add_startegies)
                this.add_startegies.startegies.push(
                    {
                        // "oriPool":"",
                        // "tarPool":"",
                        "appProtocol": "",
                        "direction": "",
                        "netId": "",
                        "oriAddr": "",
                        "oriMapAddr": "",
                        "oriPortFrom": "",
                        "oriPortTo": "",
                        "purpose": "",
                        
                        "targetAddr": "",
                        "targetMapAddr": "",
                        "targetPortTo": "",
                        "targetPortfrom": "",
                        "tcpProtocol": "",
                        "udpProtocol": ""
                    }
                )
            },
            deleteList(row,index){
                console.log("deleteList",index)
                this.add_startegies.startegies.splice(index,1)
            },
			getAllSys(){
				var url = this.CONFIG.progress_url + "/system-map/for/net"
				var that = this;
				ajax.get({
					url: url,
					that: that,
					params: null,
					success: function(data) {
						that.allSysList = data
					}
				})
            },
			changePage(page) {
				console.log('page', Object.prototype.toString.call(page) == '[object Number]')
				var that = this;
				if (page != undefined && page > 0 && page != null && Object.prototype.toString.call(page) === '[object Number]') {
					that.page = page;
				} else {
					that.page = 1;
				}
				var param = {
					current: that.page,
					pageSize: that.pageSize,
					title: this.search_param,
				}
				console.log('param:',param)
				var url = this.strategyyUrl + '/names';
				ajax.get({
					url: url,
					that: that,
					params: param,
					success: function(data) {
						console.log('changePage_data', data)
						that.startegies = data['records'];
						that.total_num = data['total'];
					}
				})
			},

			changePageSize(pageSize) {
				this.pageSize = pageSize;
				this.url_id = sessionStorage.getItem("url_id")
				if (this.url_id === "0") {
					this.get_all_strategy();
				} else if (this.url_id === "1") {
					var param = sessionStorage.getItem("param");
					this.search(param);
				}
			},


			get_all_strategy(){
				var that = this;
				var url = that.strategyyUrl + "/names";
				ajax.get({
					url: url,
					that: that,
					success: function(data) {
						console.log('get_all_strategy:', data)
						that.countSys = data
						sessionStorage.setItem("url_id", "0");
						that.changePage();
					}
				})
			},

			messageWarningFn(text) {
				this.$Message.warning(text)
				setTimeout(() => {
					this.loading = false
					this.$nextTick(() => {
						this.loading = true
					});
				}, 1);
			},

			cancel(name) {
				this.$refs[name].resetFields();
			},

			add_startegies_ok(){
				var temp_stragies = this.add_startegies.startegies
				var valid_ok = true
				temp_stragies.forEach(item=>{
					if (item['oriAddr']!='' && !this.checkIP(this.splitIP(item['oriAddr']))) {
						valid_ok = false
						this.$Message.error('请正确填写源地址IP');
					}
					if (item['oriMapAddr']!='' && !this.checkIP(this.splitIP(item['oriMapAddr']))) {
						valid_ok = false
						this.$Message.error('请正确填写源地址对应的映射IP');
					}
					if (item['targetAddr']!='' && !this.checkIP(this.splitIP(item['targetAddr']))) {
						valid_ok = false
						this.$Message.error('请正确填写目的地址IP');
					}
					if (item['targetMapAddr']!='' && !this.checkIP(this.splitIP(item['targetMapAddr']))) {
						valid_ok = false
						this.$Message.error('请正确填写目的地址对应的映射IP');
					}
				})
				if (valid_ok) {
					var that = this;
					let sys = {
						title:that.add_startegies.title,
						oriPool:that.add_startegies.oriPool,
						tarPool:that.add_startegies.tarPool,
						oriSys:that.add_startegies.oriSys,
						tarSys:that.add_startegies.tarSys,
						netType:that.add_startegies.netType,
						startegies:that.add_startegies.startegies,
					}
					var url = that.strategyyUrl;
					if (that.add_startegies.isupdate) { //说明是修改，不是新增
						sys['id'] = that.add_startegies.id,
						console.log('sys', sys)
						ajax.put({
							url: url,
							that: that,
							data: sys,
							success: function(data) {
								that.get_all_strategy();
								that.$Notice.success({
									title: '成功修改模板'
								});
								that.add_startegies.show = false;
							}
						})
					}else{//说明是新增
						console.log('新增：', that.add_startegies)
						
						console.log('sys', sys)
						ajax.post({
							url: url,
							that: that,
							data: sys,
							success: function(data) {
								that.get_all_strategy();
								that.$Notice.success({
									title: '成功新建模板'
								});
								that.add_startegies.show = false;
							}
						})
					}
				}else{
					this.$Message.error('请正确填写IP');
					this.loading = false
					this.$nextTick(() => {
						this.loading = true
					});
				}
			},


			add() {
				this.add_startegies.isupdate = false;
				this.add_startegies.show = true;
				this.add_startegies.title="";
				this.add_startegies.oriPool='';
				this.add_startegies.tarPool='';
				this.add_startegies.oriSys='';
				this.add_startegies.tarSys='';
				this.add_startegies.netType='';
				this.add_startegies.startegies=[];
			},
			in_array(list, value){
				for(var i = 0; i < list.length; i++) {
					if(list[i].sysName == value) {
						return true;
					}
				}
				return false;
			},
			edit(params) {
				console.log("params---->", params)
				var t = JSON.stringify(params)
				var temp = JSON.parse(t)
				this.add_startegies.title=temp.row.title
				this.add_startegies.oriPool=temp.row.oriPool
				this.add_startegies.tarPool=temp.row.tarPool
				this.add_startegies.oriSys=temp.row.oriSys
				this.add_startegies.tarSys=temp.row.tarSys
				this.add_startegies.netType=temp.row.netType
				this.add_startegies.startegies=temp.row.startegies

				this.add_startegies.id = temp.row.id
				this.editIndex = temp.index

				this.add_startegies.isupdate = true
				this.add_startegies.show = true;
				console.log('this.allSysList------>',this.allSysList)
			},
			delete(id) {
				console.log('delete_id', id)
				this.$Modal.confirm({
					title: '确定删除该模板？',
					width: '360',
					onOk: () => {
						this.del(id)
					}
				});
			},
			del(id) {
				sessionStorage.setItem("delete", "true");
				var that = this;
				var url = that.strategyyUrl + '/' + id;
				ajax.put({
					url: url,
					that: that,
					success: function() {
						that.url_id = sessionStorage.getItem("url_id")
						if (that.url_id === "0") {
							that.get_all_strategy();
						} else if (that.url_id === "1") {
							var param = sessionStorage.getItem("param");
							that.search(param);
						}

						if (that.data.length === 1 && that.page > 1) {
							var pageTemp = that.page - 1;
						}
						that.changePage(pageTemp);

						that.$Notice.success({
							title: '成功删除模板配置'
						});
					}
				});
			},
			search(param) {
				if (param === '') {} else {
					this.changePage(1)
				}
			},

		}
	}
</script>

<style>
  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>
